package com.cyt.work.divideclass.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.hutool.core.collection.CollUtil;
import com.cyt.base.model.dto.ReturnResult;
import com.cyt.base.util.*;
import com.cyt.sys.model.po.SysUser;
import com.cyt.sys.service.SysFileService;
import com.cyt.sys.service.impl.BaseServiceImpl;
import com.cyt.sys.util.EasyPoiUtil;
import com.cyt.sys.util.FilePathUtil;
import com.cyt.sys.util.GlobalExcelDictHandler;
import com.cyt.work.divideclass.dao.DivideclassDao;
import com.cyt.work.divideclass.dao.DivideclassStudentDao;
import com.cyt.work.divideclass.model.po.Divideclass;
import com.cyt.work.divideclass.model.po.DivideclassClass;
import com.cyt.work.divideclass.model.po.DivideclassStudent;
import com.cyt.work.divideclass.model.vo.DivideclassStudentImportVo;
import com.cyt.work.divideclass.model.vo.DivideclassStudentVerifyImportVo;
import com.cyt.work.divideclass.model.vo.DivideclassStudentVo;
import com.cyt.work.divideclass.service.DivideclassStudentService;
import com.cyt.work.enrollment.model.po.EnrollmentStuinfo;
import com.cyt.work.enrollment.model.vo.EnrollmentStuinfoImportVo;
import com.cyt.work.enrollment.model.vo.EnrollmentStuinfoVerifyImportVo;
import com.cyt.work.enrollment.model.vo.EnrollmentStuinfoVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

/**
 * 智能分班学生表,分班时导入的学生信息-智能分班学生Service层实现类
 *
 * @author caideyong
 * @date 2019-12-20 14:24:31
 */
@Service("divideclassStudentService")
public class DivideclassStudentServiceImpl extends BaseServiceImpl<DivideclassStudent> implements DivideclassStudentService {

    @Resource
    private DivideclassStudentDao divideclassStudentDao;

    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private DivideclassDao divideclassDao;

    @Autowired
    public void setBaseDao(DivideclassStudentDao divideclassStudentDao) {
        this.baseDao = divideclassStudentDao;
    }

    /**
     * 查询对象集合
     *
     * @param divideclassStudentVo 对象
     * @return List 对象集合
     * @author caideyong
     * @date 2019-12-20 14:24:31
     */
    @Override
    public List<DivideclassStudent> listExample(DivideclassStudentVo divideclassStudentVo) {
        Example example = new Example(DivideclassStudent.class);
        example.setOrderByClause(" create_time desc");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        if(StringUtils.isNotEmpty(divideclassStudentVo.getDivideId())){
            criteria.andEqualTo("divideId", divideclassStudentVo.getDivideId());
        }
        if(StringUtils.isNotEmpty(divideclassStudentVo.getClassId())){
            criteria.andEqualTo("classId",divideclassStudentVo.getClassId());
        }
        if(StringUtils.isNotEmpty(divideclassStudentVo.getName())){
            criteria.andLike("name", "%" + divideclassStudentVo.getName() + "%");
        }
        if(StringUtils.isNotEmpty(divideclassStudentVo.getSchool())){
            criteria.andLike("school","%"+divideclassStudentVo.getSchool()+"%");
        }
        if(StringUtils.isNotEmpty(divideclassStudentVo.getXh())){
            criteria.andEqualTo("xh",divideclassStudentVo.getXh());
        }
        return divideclassStudentDao.selectByExample(example);
    }

    /**
     * 分页查询
     *
     * @param divideclassStudentVo 接受参数对象
     * @param pageNum          分页数
     * @param pageSize         每页显示条数
     * @return ReturnResult
     * @author caideyong
     * @date 2019-12-20 14:24:31
     */
    @Override
    public ReturnResult page(DivideclassStudentVo divideclassStudentVo, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        PageHelper.orderBy(" xh asc");
        List<DivideclassStudent> list = listExample(divideclassStudentVo);
        PageInfo<DivideclassStudent> page = new PageInfo<>(list);
        return new ReturnResult(page.getList(), page.getTotal(), page.isHasNextPage());
    }

    /**
     * 添加或更新
     *
     * @param divideclassStudentVo 参数接受对象
     * @param sysUser      当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019-12-20 14:24:31
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult addOrUpdate(DivideclassStudentVo divideclassStudentVo, SysUser sysUser) {
        if (StringUtils.isBlank(divideclassStudentVo.getId())) {
            DivideclassStudent divideclassStudent = new DivideclassStudent(sysUser);
            divideclassStudent.setXh(divideclassStudentVo.getXh());
            divideclassStudent.setName(divideclassStudentVo.getName());
            divideclassStudent.setSex(divideclassStudentVo.getSex());
            divideclassStudent.setSchool(divideclassStudentVo.getSchool());
            divideclassStudent.setCreator(divideclassStudentVo.getCreator());
            divideclassStudent.setTotalScore(divideclassStudentVo.getTotalScore());
            divideclassStudent.setClassId(divideclassStudentVo.getClassId());
            divideclassStudent.setDivideId(divideclassStudentVo.getDivideId());
            divideclassStudent.setUserId(divideclassStudentVo.getUserId());
            divideclassStudentDao.insert(divideclassStudent);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_INSERT);
        } else {
            DivideclassStudent divideclassStudent = divideclassStudentDao.selectByPrimaryKey(divideclassStudentVo.getId());
            divideclassStudent.setXh(divideclassStudentVo.getXh());
            divideclassStudent.setName(divideclassStudentVo.getName());
            divideclassStudent.setSex(divideclassStudentVo.getSex());
            divideclassStudent.setSchool(divideclassStudentVo.getSchool());
            divideclassStudent.setCreator(divideclassStudentVo.getCreator());
            divideclassStudent.setTotalScore(divideclassStudentVo.getTotalScore());
            divideclassStudent.setClassId(divideclassStudentVo.getClassId());
            divideclassStudent.setDivideId(divideclassStudentVo.getDivideId());
            divideclassStudent.setUserId(divideclassStudentVo.getUserId());
            divideclassStudentDao.updateByPrimaryKey(divideclassStudent);
            return new ReturnResult(BaseConstant.DATABASE_SUCCEED_UPDATE);
        }
    }

    /**
     * 根据条件逻辑删除
     *
     * @param divideclassStudentVo 参数接受对象
     * @param sysUser 当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019-12-20 14:24:31
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult remove(DivideclassStudentVo divideclassStudentVo, SysUser sysUser) {
        //要修改的字段
        DivideclassStudent divideclassStudent = new DivideclassStudent();
        divideclassStudent.setRemoveTag(DictCode.BASE_REMOVE_TAG_DELETE);
        //筛选条件
        Example example = new Example(DivideclassStudent.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(divideclassStudentVo.getId())) {
            criteria.andIn("id", Arrays.asList(divideclassStudentVo.getId().split(",")));
        }
        if(StringUtils.isNotEmpty(divideclassStudentVo.getDivideId())){
            criteria.andEqualTo("divideId",divideclassStudentVo.getDivideId());
        }
        criteria.andEqualTo("removeTag", DictCode.BASE_REMOVE_TAG_NORMAL);
        divideclassStudentDao.updateByExampleSelective(divideclassStudent, example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    /**
     * 根据条件物理删除
     *
     * @param divideclassStudentVo 参数接受对象
     * @param sysUser      当前用户
     * @return ReturnResult
     * @author caideyong
     * @date 2019-12-20 14:24:31
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnResult delete(DivideclassStudentVo divideclassStudentVo, SysUser sysUser) {
        //筛选条件
        Example example = new Example(DivideclassStudent.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(divideclassStudentVo.getId())) {
            criteria.andIn("id", Arrays.asList(divideclassStudentVo.getId().split(",")));
        }
        divideclassStudentDao.deleteByExample(example);
        return new ReturnResult(ErrorCode.CODE_0, BaseConstant.DATABASE_SUCCEED_DEL);
    }

    @Override
    public void insertList(List<DivideclassStudent> divideclassStudentList) {
        divideclassStudentDao.insertList(divideclassStudentList);
    }

    @Override
    public void export(HttpServletResponse response, DivideclassStudentVo divideclassStudentVo) {
        List<DivideclassStudent> divideclassStudentList=listExample(divideclassStudentVo);
        EasyPoiUtil.exportExcel(divideclassStudentList,"智能分班学生表","智能分班学生表",DivideclassStudent.class,"智能分班学生表.xls",response);
    }

    /**
     * 导入学生信息
     *
     * @return ReturnResult
     * @author caideyong
     * @date 2019/12/27
     */
    @Override
    public ReturnResult importData(HttpServletRequest request, MultipartFile file, String catalog, String update, String applyId, SysUser sysUser, String divideId) {
        // 1、不更新已存在数据，2、更新存在数据
        ReturnResult returnResult = sysFileService.fileUpload(file, request, catalog, BaseConstant.FILE_TYPE_EXECL);
        if (ErrorCode.CODE_0 == returnResult.getCode()) {
            String filePath = FilePathUtil.acceptCheckRealPath(request) + returnResult.getData().toString();
            ImportParams params = new ImportParams();
            params.setTitleRows(0);
            params.setHeadRows(1);
            params.setNeedVerify(true);
            // 解决多读取问题，如果出现没有导入问题，需要将该属性去除
            params.setKeyIndex(0);
            // 如果有code码需要设置，现有bug，需要修改源码CellValueService
            params.setDictHandler(new GlobalExcelDictHandler());
            ExcelImportResult<DivideclassStudentVerifyImportVo> result = ExcelImportUtil.importExcelMore(new File(filePath), DivideclassStudentVerifyImportVo.class, params);
            List<DivideclassStudentVerifyImportVo> educationUserImportList = result.getList();
            if (CollUtil.isNotEmpty(educationUserImportList)) {
                //先删除已有的数据
                DivideclassStudentVo e = new DivideclassStudentVo();
                e.setDivideId(divideId);
                this.remove(e, sysUser);
                Map<String, DivideclassStudentImportVo> educationUserMap = new HashMap<>();
                String key;
                for (DivideclassStudentImportVo educationUser : educationUserImportList) {
                    key = educationUser.getXh();
                    if (educationUserMap.keySet().contains(key)) {
                        continue;
                    }
                    educationUserMap.put(key, educationUser);
                }
                List<DivideclassStudent> divideclassStudentList = new ArrayList<>();
                for (Map.Entry<String, DivideclassStudentImportVo> entry : educationUserMap.entrySet()) {
                    // 名称不存在
                    DivideclassStudentImportVo userFrom = entry.getValue();
                    DivideclassStudent divideclassStudent = new DivideclassStudent();
                    divideclassStudent.setId(BaseUtil.uId());
                    divideclassStudent.setDivideId(divideId);
                    divideclassStudent.setName(userFrom.getName());
                    divideclassStudent.setSchool(userFrom.getSchool());
                    divideclassStudent.setSex(userFrom.getSex());
                    divideclassStudent.setCreateTime(new Date());
                    divideclassStudent.setCreator(sysUser.getId());
                    divideclassStudent.setXh(userFrom.getXh());
                    divideclassStudent.setRemoveTag(BaseConstant.REMOVE_TAG_NO);
                    divideclassStudentList.add(divideclassStudent);
                }
                // 保存
                if (divideclassStudentList != null && divideclassStudentList.size() > 0) {
                    this.insertList(divideclassStudentList);
                    //保存分班学生数量
                    Divideclass divideclass=divideclassDao.selectByPrimaryKey(divideId);
                    if(divideclass!=null){
                        divideclass.setDivideNum(divideclassStudentList.size()+"");
                        divideclassDao.updateByPrimaryKey(divideclass);
                    }
                }
            } else {
                // 行号从0开始，要加上titleRows和headRows
                if (result.isVerfiyFail()) {
                    // 如果错误，打印出提醒，直接返回
                    int successNum = 0;
                    int failNum = result.getFailList().size();
                    if (result.getList() != null && result.getList().size() > 0) {
                        successNum = result.getList().size();
                    }
                    String errorMsg = String.format("共导入%s条，成功%s条，失败%s条。", successNum + failNum, successNum, failNum);
                    List<DivideclassStudentVerifyImportVo> failList = result.getFailList();
                    return new ReturnResult(ErrorCode.CODE_1, failList, errorMsg);
                }
            }
        }
        return returnResult; // 1、不更新已存在数据，2、更新存在数据
    }
}